/*第一步：声明构造函数*/
function Axios(config) {
  this.config = config
}

Axios.prototype.request = function (config) {
  //创建一个promise对象
  let promise = Promise.resolve(config)
  let chains = [dispatchRequest, undefined]
  let result = promise.then(chains[0], chains[1])
  return result;
}

/*第二步*/
function dispatchRequest(config) {
  return xhrAdapter(config).then(response => {
    // console.log(response,"111")
    return response
  }, error => {
    // console.log(error)
    throw error
  })
}

/*第三步*/
function xhrAdapter(config) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest()
    xhr.responseType = "json"
    xhr.timeout = 3000
    xhr.ontimeout = function (err) {
      console.log(err)
    }
    xhr.onerror = err => {
      console.log(err)
    }
    //拼接baseurl和url
    var url = config.baseUrl + config.url
    
    //如果有参数，拼接参数
    if (config.data) {
      var dataArr = []
      for (var i in config.data) {
        dataArr.push(i + "=" + config.data[i])
      }
      url += "?" + dataArr.join("&")
    }


    xhr.open(config.method || "GET", url)
    xhr.send()
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
          resolve({
            config: config,    //配置对象
            data: xhr.response,   //响应体
            headers: xhr.getAllResponseHeaders(),  //字符串
            request: xhr,    //请求对象
            status: xhr.status,    //响应状态码
            statusText: xhr.statusText    //响应状态字符串

          })
        } else {
          reject(new Error("请求失败，状态码为" + xhr.status))
        }
      }
    }
  })


}

// 第四步
let axios = Axios.prototype.request.bind(null)

export default axios;
